package com.xyh.reward_kotlin.fragments

import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.InputType
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.graphics.toColorInt
import androidx.fragment.app.Fragment
import com.xyh.reward_kotlin.R
import com.google.android.material.card.MaterialCardView
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.xyh.reward_kotlin.api.ApiCallback
import com.xyh.reward_kotlin.api.ApiClient
import com.xyh.reward_kotlin.api.RewardApi
import com.xyh.reward_kotlin.filter.InputFilterMinMax
import com.xyh.reward_kotlin.response.RewardResultDto
import com.xyh.reward_kotlin.response.StudentDto
import com.xyh.reward_kotlin.response.Subject

class CalculatorFragment : Fragment() {

    private lateinit var subjectContainer: LinearLayout
    private lateinit var resultContainer: LinearLayout
    private lateinit var overviewContainer: LinearLayout
    private lateinit var resultCard: MaterialCardView
    private lateinit var editRank: EditText
    private lateinit var spinKit: View

    private val subjectEditMap: MutableMap<String, EditText> = mutableMapOf()

    private val rewardApi: RewardApi = ApiClient.client.create(RewardApi::class.java)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        Log.d("calculator", "onCreateView: 初始化页面")
        val rootView = inflater.inflate(R.layout.fragment_calculator, container, false)

        spinKit = rootView.findViewById(R.id.spin_kit)
        subjectContainer = rootView.findViewById(R.id.subjectContainer)
        resultContainer = rootView.findViewById(R.id.rewardContainerLayout)
        overviewContainer = rootView.findViewById(R.id.overviewContainer)
        resultCard = rootView.findViewById(R.id.resultCard)
        editRank = rootView.findViewById(R.id.editRank)

        editRank.filters = arrayOf(InputFilterMinMax(1, Int.MAX_VALUE))

        rootView.findViewById<Button>(R.id.btnCalculate).setOnClickListener {
            Log.d("calculator", "点击计算按钮")
            calculateReward(rootView)
        }

        loadSubjects(rootView)
        return rootView
    }

    private fun loadSubjects(rootView: View) {
        spinKit.visibility = View.VISIBLE
        Log.d("calculator", "loadSubjects: 开始加载科目")
        cachedSubjects?.let {
            Log.d("calculator", "使用缓存科目数量: ${it.size}")
            it.forEach { subject -> addSubjectInput(subject) }
            spinKit.visibility = View.GONE
            return
        }

        rewardApi.getSubjects().enqueue(object : ApiCallback<List<Subject>>() {
            override fun onSuccess(result: List<Subject>) {
                Log.d("calculator", "科目接口返回数量: ${result.size}")
                cachedSubjects = result
                result.forEach { subject -> addSubjectInput(subject) }
                spinKit.visibility = View.GONE
            }

            override fun onError(errorMsg: String?) {
                Log.e("calculator", "加载科目失败: $errorMsg")
                Snackbar.make(rootView, "加载科目失败：$errorMsg", Snackbar.LENGTH_LONG).show()
                spinKit.visibility = View.GONE
            }
        })
    }

    private fun addSubjectInput(subject: Subject) {
        Log.d("calculator", "addSubjectInput: ${subject.name}, 满分=${subject.full}")
        val inflater = LayoutInflater.from(context)
        val inputView = inflater.inflate(R.layout.item_subject_input, subjectContainer, false)
        val inputLayout = inputView.findViewById<TextInputLayout>(R.id.inputLayout)
        val editText = inputView.findViewById<TextInputEditText>(R.id.editText)

        inputLayout.hint = "${subject.name}成绩（满分${subject.full}）"
        editText.inputType = InputType.TYPE_CLASS_NUMBER
        editText.filters = arrayOf(InputFilterMinMax(0, subject.full!!))

        subjectEditMap[subject.name as String] = editText
        subjectContainer.addView(inputView)
    }

    private val studentDto: StudentDto?
        get() {
            var hasError = false
            val scores = mutableMapOf<String, Int>()

            subjectEditMap.forEach { (subject, edit) ->
                val value = edit.text.toString().trim()
                Log.d("calculator", "录入成绩: $subject=$value")
                if (value.isEmpty()) {
                    edit.error = "请输入$subject 成绩"
                    hasError = true
                } else scores[subject] = value.toInt()
            }

            if (editRank.text.toString().trim().isEmpty()) {
                Log.d("calculator", "排名输入为空")
                editRank.error = "请输入排名"
                hasError = true
            }

            return if (hasError) {
                Log.w("calculator", "输入校验失败")
                null
            } else {
                Log.d("calculator", "studentDto生成 scores=$scores, rank=${editRank.text}")
                StudentDto(scores, editRank.text.toString().toInt())
            }
        }

    private fun calculateReward(rootView: View) {
        val request = studentDto ?: return
        Log.d("calculator", "开始计算奖励: $request")
        spinKit.visibility = View.VISIBLE

        rewardApi.calculateReward(request).enqueue(object : ApiCallback<RewardResultDto>() {
            override fun onSuccess(result: RewardResultDto) {
                Log.d("calculator", "奖励计算成功: $result")
                setSuccessResult(result)
                spinKit.visibility = View.GONE
            }

            override fun onError(errorMsg: String?) {
                Log.e("calculator", "计算奖励失败: $errorMsg")
                Snackbar.make(rootView, "计算出错：$errorMsg", Snackbar.LENGTH_LONG).show()
                spinKit.visibility = View.GONE
            }
        })
    }

    private fun setSuccessResult(result: RewardResultDto) {
        Log.d("calculator", "展示奖励结果: totalReward=${result.totalReward}, base=${result.base}, extra=${result.extra}, special=${result.special}")
        resultCard.visibility = View.VISIBLE
        overviewContainer.removeAllViews()
        resultContainer.removeAllViews()

        val totalDesc = """
            奖励总金额：${result.totalReward}
            总分：${result.total}（核心：${result.coreTotal}，综合：${result.generalTotal}）
            当前排名：${result.currentRank}
        """.trimIndent()
        addRewardOverviewCard(totalDesc)

        val rewardMap = linkedMapOf(
            "基础奖励（${result.base}）" to "达标条件：${result.baseDesc}",
            "额外奖励（${result.extra}）" to "额外条件：${result.extraDesc}",
            "特殊奖励（${result.special}）" to "特殊说明：${result.specialDesc}"
        )

        rewardMap.forEach { (key, value) ->
            resultContainer.addView(createRewardCard(key, value))
        }
    }

    private fun addRewardOverviewCard(totalDesc: String) {
        val context = requireContext()

        overviewContainer.removeAllViews()

        val divider = View(context)
        divider.layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, 1
        ).apply { setMargins(0, 16, 0, 16) }
        divider.setBackgroundColor("#DDDDDD".toColorInt())
        overviewContainer.addView(divider)

        val titleView = TextView(context).apply {
            text = "奖励概览"
            setTextColor(ContextCompat.getColor(context, R.color.black))
            textSize = 18f
            setTypeface(Typeface.DEFAULT_BOLD)
            layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
            )
        }
        overviewContainer.addView(titleView)

        val contentView = TextView(context).apply {
            text = totalDesc
            textSize = 16f
            setTextColor(Color.DKGRAY)
            setPadding(0, 8, 0, 0)
        }
        overviewContainer.addView(contentView)
    }

    private fun createRewardCard(title: String, content: String): View {
        val context = requireContext()
        val card = MaterialCardView(context).apply {
            layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            ).apply { setMargins(0, 0, 0, 16) }
            cardElevation = 2f
            strokeWidth = 1
            strokeColor = ContextCompat.getColor(context, R.color.gray)
            radius = 8f
            backgroundTintList = ColorStateList.valueOf(Color.WHITE)
        }

        val layout = LinearLayout(context).apply {
            orientation = LinearLayout.VERTICAL
            setPadding(24, 24, 24, 24)
        }

        val titleView = TextView(context).apply {
            text = title
            textSize = 16f
            setTypeface(null, Typeface.BOLD)
            setTextColor(ContextCompat.getColor(context, R.color.black))
        }
        val contentView = TextView(context).apply {
            text = content
            textSize = 14f
            setPadding(0, 8, 0, 0)
            setTextColor(ContextCompat.getColor(context, R.color.black))
        }

        layout.addView(titleView)
        layout.addView(contentView)
        card.addView(layout)

        return card
    }

    companion object {
        private var cachedSubjects: List<Subject>? = null
    }
}